package com.chilly.tx;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * spring 事务
 * Created by Chilly Cui on 2020/9/25.
 */
public class TxDemo {

    @Autowired
    private TransactionTemplate transactionTemplate;

    //编程式事务管理
    @Test
    void testBianChengTx() {
        //使用TransactionTemplate 进行编程式事务管理的示例代码如下：
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                try {

                    // ....  业务代码
                } catch (Exception e) {
                    //回滚
                    transactionStatus.setRollbackOnly();
                }
            }
        });
    }

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Test
    void testBianChengTx2() {
        //使用 TransactionManager 进行编程式事务管理的示例代码如下：
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            // ....  业务代码
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
        }
    }


    //声明式事务管理
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)
    void testTx(){
        //do something
    }


}